package com.pumpkin.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pumpkin.server.commons.ResBean;
import com.pumpkin.server.pojo.Menu;
import com.pumpkin.server.pojo.Role;
import com.pumpkin.server.pojo.RoleMenu;
import com.pumpkin.server.service.IMenuService;
import com.pumpkin.server.service.IRoleMenuService;
import com.pumpkin.server.service.IRoleService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.lang.model.type.ErrorType;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 权限组
 */

@RestController
@RequestMapping("/system/basic/permission")
public class PermissionController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IMenuService menuService;

    @Autowired
    private IRoleMenuService roleMenuService;

    /**
     * 获取所有角色
     * @return
     */
    @ApiOperation(value = "获取所有角色")
    @GetMapping("/")
    public List<Role> getAllRoles() {
        return roleService.list();
    }

    /**
     * 添加角色
     * @param role
     * @return
     */
    @ApiOperation(value = "添加角色")
    @PostMapping("/role")
    public ResBean addRole(@RequestBody Role role) {
        if (!role.getName().startsWith("ROLE_")) {
            role.setName("ROLE_" + role.getName());
        }
        if (roleService.save(role)) {
            return ResBean.success("添加成功！");
        }
        return ResBean.error("添加失败！");
    }

    /**
     * 删除角色
     * @param rid
     * @return
     */
    @ApiOperation(value = "删除角色")
    @DeleteMapping("/role/{rid}")
    public ResBean deleteRole(@PathVariable Integer rid) {
        if (roleService.removeById(rid)) {
            return ResBean.success("删除成功！");
        }
        return ResBean.error("删除失败！");
    }

    /**
     * 查询所有菜单及其子菜单
     * @return
     */
    @ApiOperation(value = "查询所有菜单及其子菜单")
    @GetMapping("/menus")
    public List<Menu> getAllMenus() {
        return menuService.getAllMenus();
    }

    /**
     * 根据角色id查询菜单id
     * @param rid
     * @return
     */
    @ApiOperation(value = "根据角色id查询菜单id")
    @GetMapping("/mid/{rid}")
    public List<Integer> getMidByRid(@PathVariable Integer rid) {
        return roleMenuService.list(new QueryWrapper<RoleMenu>().eq("roleId",rid)).stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
    }

    /**
     * 更新角色菜单
     * @param rid
     * @param mids
     * @return
     */
    @ApiOperation(value = "更新角色菜单")
    @PutMapping("/")
    public ResBean updateMenuRole(Integer rid,Integer[] mids) {
        return roleMenuService.updateMenuRole(rid,mids);
    }
}
